import moment from "moment";
import { cloneDeep, map } from "lodash";
import { formatUnit, IUnit, formatChartTooltip } from "./format";

export const basiclineOption = {
  title: {
    show: false,
    text: "",
    textStyle: {
      fontSize: 12,
    },
  },
  tooltip: {
    trigger: "axis",
    order: "valueDesc",
    confine: true,
  },
  legend: {
    show: true,
    icon: "roundRect",
    type: "scroll",
    left: 10,
    top: 0,
    itemWidth: 10,
    itemHeight: 10,
    data: [],
  },
  grid: {
    left: 20,
    top: 40,
    right: 10,
    bottom: 20,
    containLabel: true,
  },
  xAxis: [
    {
      type: "category",
      boundaryGap: false,
      data: [],
      axisLabel: {
        formatter: (v) => moment(v).format("MM-DD HH:mm"),
      },
    },
  ],
  yAxis: [
    {
      type: "value",
      axisLabel: {},
    },
  ],
  series: [],
};

const alarmSeriesColor = [
  "rgba(247, 49, 59, 0.7)",
  "rgba(235, 187, 77, 0.7)",
  "rgba(222, 212, 15, 0.7)",
  "rgba(34, 110, 231, 0.7)",
  "rgba(19, 194, 194, 0.7)",
];
export const alarmPieOption = {
  color: alarmSeriesColor,
  title: {
    show: true,
    text: "",
    textStyle: {
      fontSize: 24,
      fontWeight: 500,
      color: "rgba(0, 0, 0, 0.85)",
    },
    subtext: "未关闭告警数",
    subtextStyle: {
      fontSize: 12,
      fontWeight: 400,
      color: "rgba(0, 0, 0, 0.45)",
    },
    itemGap: 5,
    left: "center",
    top: "38%",
  },
  tooltip: {
    trigger: "item",
    confine: true,
  },
  legend: {
    show: false,
    icon: "roundRect",
    type: "scroll",
    left: 10,
    top: 0,
    itemWidth: 10,
    itemHeight: 10,
  },
  series: [
    {
      name: "未关闭告警数",
      type: "pie",
      radius: ["50%", "75%"],
      label: {
        formatter: (params) => `${params.percent}%`,
      },
      data: [],
    },
  ],
};

export const alarmBarOption = {
  color: alarmSeriesColor,
  title: {
    show: false,
  },
  tooltip: {
    trigger: "axis",
    order: "seriesAsc",
    confine: true,
  },
  legend: {
    show: true,
    icon: "roundRect",
    type: "scroll",
    left: 0,
    top: 0,
    itemWidth: 10,
    itemHeight: 10,
  },
  grid: {
    left: 0,
    top: 40,
    right: 10,
    bottom: 0,
    containLabel: true,
  },
  xAxis: [
    {
      type: "category",
      // boundaryGap: false,
      data: [],
      axisLabel: {
        formatter: (v) => moment(v).format("MM-DD HH:mm"),
      },
    },
  ],
  yAxis: [
    {
      type: "value",
      axisLabel: {},
    },
  ],
  series: [
    {
      name: "P1",
      type: "bar",
      stack: "total",
      emphasis: {
        focus: "series",
      },
      data: [],
    },
    {
      name: "P2",
      type: "bar",
      stack: "total",
      emphasis: {
        focus: "series",
      },
      data: [],
    },
    {
      name: "P3",
      type: "bar",
      stack: "total",
      emphasis: {
        focus: "series",
      },
      data: [],
    },
    {
      name: "P4",
      type: "bar",
      stack: "total",
      emphasis: {
        focus: "series",
      },
      data: [],
    },
    {
      name: "P5",
      type: "bar",
      stack: "total",
      emphasis: {
        focus: "series",
      },
      data: [],
    },
  ],
};

export const lineWithoutAxis = {
  tooltip: {
    trigger: "axis",
  },
  grid: {
    left: 0,
    top: 1,
    right: 0,
    bottom: 1,
  },
  xAxis: [
    {
      show: false,
      type: "category",
    },
  ],
  yAxis: [
    {
      show: false,
    },
  ],
  series: [],
};

export const buildLineSeriesData = (
  name,
  data,
  areaStyle = { opacity: 0.12 },
  type = "line"
) => {
  return {
    name: name,
    type: type,
    data: data,
    areaStyle: areaStyle,
    smooth: false,
    connectNulls: true,
    showSymbol: false,
  };
};

export const top5lineDataHandle = (
  data,
  field,
  chartField,
  unit,
  valueField = "value"
) => {
  const options = cloneDeep(basiclineOption);
  if (!data?.length) {
    return options;
  }
  options.xAxis[0].data = map(data[0][chartField], "time");
  options.legend.data = map(data, field);
  options.grid.top = 40;
  options.yAxis[0].axisLabel.formatter = (v) => formatUnit(v, unit);
  data.forEach((item) => {
    options.series.push(
      buildLineSeriesData(item[field], map(item[chartField], valueField))
    );
  });
  options.tooltip.formatter = (data) => formatChartTooltip(data, unit);
  return options;
};

/**
 * 多胞折线图处理公共方法
 * @param data
 * @param name
 * @param unit
 * @param field
 * @returns
 */
export const multipleLineOptionHandle = (
  data,
  name,
  unit,
  ceil = "none",
  nameZh = "none"
) => {
  const options = _.cloneDeep(basiclineOption);
  const { port, pid } = ceil;
  options.extra = { port: port, pid: pid };
  options.xAxis[0].data = _.map(data, "time");

  options.yAxis[0].axisLabel.formatter = (v) => formatUnit(v, unit);
  name.length > 0
    ? name.map((items, idx) => {
        options.legend.data.push(nameZh[idx]);
        options.series.push(
          buildLineSeriesData(nameZh[idx], _.map(data, items))
        );
      })
    : (() => {
        options.legend.data.push("");
        options.series.push(buildLineSeriesData("", _.map(data, "")));
      })();
  // options.tooltip.formatter = (data) => formatChartTooltip(data, unit);

  options.tooltip.formatter = (
    params,
    unit1,
    total,
    unit2,
    withoutUnit2Field
  ) => {
    let count = 0;
    let result = `<div style="min-width:200px"><div>${params[0].axisValue}</div>`;
    // 悬浮框tooltip展示按大小从上到下排序
    params.sort((a, b) => b.value - a.value);
    _.forEach(params, (item, index) => {
      if (
        typeof item.value !== "undefined" &&
        typeof item.value !== "object" &&
        item.value !== "-"
      ) {
        const field1 = formatUnit(item.value, unit1);
        let field2;
        // 提供unit2并且当前系列名字不是withoutUnit2Field，则计算field2并展示
        if (unit2 && item.seriesName !== withoutUnit2Field && total) {
          if (unit2 === "%") {
            // unit2为%，field2=item.value/total
            field2 = formatUnit(item.value / total, "100%");
          } else {
            const dataY = unit1 === "%" ? item.value / 100 : item.value;
            field2 = formatUnit(dataY * total, unit2);
          }
        }
        result += `<div>
                  <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color: ${
                    item.color
                  };"></span>
                  <span class="seriesName" data-index="${index}" data-value="${
          item.seriesName
        }" style="max-width:300px;word-break:break-all; word-wrap:break-word; white-space:pre-line;">${
          item.seriesName
        } &nbsp;&nbsp; </span>
                  <span style="">${
                    field2 ? `${field2} (${field1})` : `${field1}`
                  }</span>
                  <span style="float:right">总量 ${
                    item.seriesName == "全连接"
                      ? data[0].acceptMax
                      : data[0].synMax
                  }</span>
              </div>`;
        count++;
      }
    });
    if (count === 0) {
      return null;
    } else {
      result += "</div>";
      return result;
    }
  };

  return options;
};

